package com.xiangty.partition;

import com.xiangty.mapper.CustTempMapper;
import org.springframework.batch.core.partition.support.Partitioner;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.Map;

@Component
public class CustTempToInfoPartitioner implements Partitioner {

    @Autowired
    private CustTempMapper custTempMapper;


    @Override
    public Map<String, ExecutionContext> partition(int gridSize) {
        System.out.println("partition  gridsize is " + gridSize);
        Map<String, ExecutionContext> result = new HashMap<>();

        Map<String, Object> map = custTempMapper.selectTempStatisticData();

        int min = 0;
        int max = 0;
        if (!CollectionUtils.isEmpty(map) && map.get("minid") != null && map.get("maxid") != null) {
            min = Integer.parseInt(map.get("minid").toString());
            max = Integer.parseInt(map.get("maxid").toString());
        }

        gridSize = gridSize > 0 ? gridSize : 1;

        // 每篇的数量
        int range = (max - min + 1) / gridSize + 1;

        System.out.println("总数量：【" + (max - min + 1) + "】---分片数量:【" + gridSize + "】---每篇数量：【" + range + "】");

        int fromId = min;
        int toId = min + range;

        for (int i = 1; i <= gridSize; i++) {
            ExecutionContext value = new ExecutionContext();
            System.out.println("Starting : Thread" + i + "  fromId : " + fromId + " toId : " + toId + " \n");

            value.putInt("fromId", fromId);
            value.putInt("toId", toId);

            // 每片数量
            value.putInt("range", range);

            // give each thread a name, thread 1,2,3
            value.putString("name", "Thread" + i);

            result.put("partition" + i, value);

            fromId = toId + 1;
            toId += range;
        }
        return result;
    }


}
